package com.jr9z.jrjz.controller;

import com.jr9z.jrjz.utils.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: MrZcc
 * @Description:
 * @Date: Created in 15:59 2019-4-12
 * @Modified By:
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {

    private final ResourceLoader resourceLoader;
    @Value("${web.upload-path}")
    private String path;
    @Value("${server.port}")
    private String port;

    public FileUploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public static void main(String[] args) throws IOException {
        //        String path=ClassUtils.getDefaultClassLoader().getResource("static").getPath()+"static/images/";


        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) path = new File("");
        System.out.println("path:" + path.getAbsolutePath());

       //如果上传目录为/static/images/upload/，则可以如下获取：
        File upload = new File(path.getAbsolutePath(), "static/images/");
        if (!upload.exists()) upload.mkdirs();
        System.out.println("upload url:" + upload.getAbsolutePath());

    }

    /**
     * @param file 要上传的文件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public Map<String, String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        Map<String, String> map = new HashMap<>();

//        String filePath = request.getSession().getServletContext().getRealPath(path);

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/images/";

        //生成随机字符串，用于图片命名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 获得文件类型
        String fileType = file.getContentType();
        // 获得文件后缀名称
        String imageName = fileType.substring(fileType.indexOf("/") + 1);
        // 原名称
//        String fileName = file.getOriginalFilename();
        // 新名称
        String newFileName = uuid + "." + imageName;

        System.out.println(imageName);

        try {
            FileUtils.upload(file.getBytes(), path, newFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 拼接图片url
        String imgHost = "http://47.95.217.210:" + port;
//        String imgUploadPath = path;
        String imgName = newFileName;
        String imgPath = imgHost + "/images/" + imgName;
        map.put("url", imgPath);
        return map;

    }

    /**
     * @param file 要上传的文件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/imgUpload", method = RequestMethod.POST)
    public Map<String, Object> imgUpload(MultipartFile file, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();

//        String filePath = request.getSession().getServletContext().getRealPath(path);

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/images/";

        //生成随机字符串，用于图片命名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 获得文件类型
        String fileType = file.getContentType();
        // 获得文件后缀名称
        String imageName = fileType.substring(fileType.indexOf("/") + 1);
        // 原名称
//        String fileName = file.getOriginalFilename();
        // 新名称
        String newFileName = uuid + "." + imageName;

        System.out.println(imageName);

        try {
            FileUtils.upload(file.getBytes(), path, newFileName);
            map.put("code", 0);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -1);
        }

        // 拼接图片url
        String imgHost = "http://47.95.217.210:" + port;
//        String imgUploadPath = path;
        String imgName = newFileName;
        String imgPath = imgHost + "/images/" + imgName;

        map.put("url", imgPath);
        return map;

    }

}
